<!--
 * @Author: Easycome 2684545336@qq.com
 * @Date: 2025-03-19 19:26:40
 * @LastEditors: Easycome 2684545336@qq.com
 * @LastEditTime: 2025-04-19 23:29:42
 * @FilePath: \yupao-frontend-master\src\pages\CommunityPage.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="community-page">
    <van-nav-bar title="社区" fixed placeholder>
      <template #right>
        <van-icon name="plus" size="18" @click="showPublish" />
      </template>
    </van-nav-bar>
    
    <div class="page-content">
      <!-- 动态列表 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-if="dynamicList.length === 0 && !loading" class="empty-container">
            <van-empty description="暂无动态内容" />
          </div>
          <div v-for="item in dynamicList" :key="item.dynamicId" class="dynamic-item">
            <div class="dynamic-header">
              <div class="user-info">
                <img :src="item.user.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" class="avatar" />
                <div class="name-time">
                  <div class="username">{{ item.user.username }}</div>
                  <div class="time">{{ formatTime(item.createTime) }}</div>
                </div>
              </div>
              <div class="options" v-if="currentUser && currentUser.id === item.userId">
                <van-icon name="delete-o" @click="confirmDelete(item.dynamicId)" />
              </div>
            </div>
            <div class="dynamic-content" @click="viewDynamicDetail(item.dynamicId)">
              <div class="text">{{ item.content }}</div>
              <div class="notice-text" v-if="item.mediaUrls && item.mediaUrls.length > 0">
                <van-tag type="warning">该版本仅支持查看文字内容</van-tag>
              </div>
            </div>
            <div class="dynamic-footer">
              <div class="action-item" @click="toggleLike(item)">
                <van-icon :name="item.hasLiked ? 'like' : 'like-o'" :color="item.hasLiked ? '#ee0a24' : ''" />
                <span>{{ item.likeCount || 0 }}</span>
              </div>
              <div class="action-item" @click="viewDynamicDetail(item.dynamicId)">
                <van-icon name="chat-o" />
                <span>{{ item.commentCount || 0 }}</span>
              </div>
              <div class="action-item">
                <van-icon name="share-o" />
                <span>{{ item.shareCount || 0 }}</span>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    
    <!-- 发布动态弹窗 -->
    <van-popup
      v-model:show="showPublishPopup"
      position="bottom"
      round
      closeable
      :style="{ height: '60%' }"
    >
      <div class="publish-header">
        <div class="publish-title">发布动态</div>
        <div class="publish-notice">当前版本仅支持发布文字动态</div>
      </div>
      <div class="publish-content">
        <van-field
          v-model="newPost"
          type="textarea"
          placeholder="分享新鲜事..."
          rows="6"
          autosize
          class="publish-textarea"
        />
      </div>
      <div class="publish-footer">
        <van-button type="default" size="small" round @click="showPublishPopup = false">取消</van-button>
        <van-button type="primary" size="small" round @click="publishPost" :disabled="!newPost.trim()">发布</van-button>
      </div>
    </van-popup>

    <!-- 操作结果提示 -->
    <van-dialog v-model:show="successDialogVisible" title="操作成功" confirm-button-text="确定">
      <div class="success-info">
        <van-icon name="success" color="#07c160" size="40" />
        <p>动态发布成功！</p>
        <div class="dynamic-info" v-if="createdDynamic">
          <p><strong>动态ID：</strong>{{ createdDynamic.dynamicId }}</p>
          <p><strong>内容：</strong>{{ createdDynamic.content }}</p>
          <p><strong>发布时间：</strong>{{ createdDynamic.createTime }}</p>
        </div>
      </div>
    </van-dialog>

    <!-- 删除确认对话框 -->
    <van-dialog
      v-model:show="deleteConfirmVisible"
      title="删除动态"
      show-cancel-button
      @confirm="deleteConfirmed"
    >
      <p class="delete-confirm-text">确定要删除这条动态吗？</p>
    </van-dialog>

    <!-- 动态评论弹窗 -->
    <van-popup
      v-model:show="commentPopupVisible"
      position="bottom"
      round
      closeable
      :style="{ height: '75%' }"
    >
      <div class="comment-header">
        <div class="comment-title">评论 ({{ commentTotal }})</div>
      </div>
      
      <!-- 评论列表 -->
      <div class="comment-list-container">
        <van-pull-refresh v-model="commentRefreshing" @refresh="refreshComments">
          <van-list
            v-model:loading="commentLoading"
            :finished="commentFinished"
            finished-text="没有更多评论"
            @load="loadMoreComments"
          >
            <div v-if="commentList.length === 0 && !commentLoading" class="empty-comment">
              <van-empty description="暂无评论" />
            </div>
            
            <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
              <div class="comment-user-info">
                <img :src="comment.user.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" class="comment-avatar" />
                <div class="comment-user-detail">
                  <div class="comment-username">{{ comment.user.username }}</div>
                  <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
                </div>
                <div class="comment-actions-top">
                  <van-icon 
                    v-if="currentUser && comment.userId === currentUser.userId" 
                    name="delete-o" 
                    @click="confirmDeleteComment(comment)" 
                    class="delete-icon"
                  />
                  <div class="comment-like">
                    <van-icon :name="comment.hasLiked ? 'like' : 'like-o'" :color="comment.hasLiked ? '#ee0a24' : ''" />
                    <span>{{ comment.likeCount || 0 }}</span>
                  </div>
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              
              <!-- 回复列表 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
                <div v-for="reply in comment.replies" :key="reply.commentId" class="reply-item">
                  <div class="reply-user-info">
                    <img :src="reply.user.avatarUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" class="reply-avatar" />
                    <div class="reply-user-detail">
                      <div class="reply-username">{{ reply.user.username }}</div>
                      <div class="reply-time">{{ formatTime(reply.createTime) }}</div>
                    </div>
                    <div class="reply-like">
                      <van-icon :name="reply.hasLiked ? 'like' : 'like-o'" :color="reply.hasLiked ? '#ee0a24' : ''" />
                      <span>{{ reply.likeCount || 0 }}</span>
                    </div>
                  </div>
                  <div class="reply-content">{{ reply.content }}</div>
                </div>
              </div>
              
              <div class="comment-actions">
                <van-button size="mini" plain @click="showReplyInput(comment)">回复</van-button>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
      
      <!-- 评论输入框 -->
      <div class="comment-input-container">
        <van-field
          v-model="newComment"
          placeholder="写评论..."
          type="text"
          class="comment-input"
          :autofocus="true"
        >
          <template #button>
            <van-button 
              size="small" 
              type="primary" 
              @click="submitComment" 
              :disabled="!newComment.trim()"
            >
              发送
            </van-button>
          </template>
        </van-field>
      </div>
    </van-popup>

    <!-- 删除评论确认对话框 -->
    <van-dialog
      v-model:show="deleteCommentConfirmVisible"
      title="删除评论"
      show-cancel-button
      @confirm="deleteCommentConfirmed"
    >
      <p class="delete-confirm-text">确定要删除这条评论吗？</p>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { 
  showSuccessToast, 
  showFailToast, 
  showLoadingToast,
  showConfirmDialog
} from "vant";
import { getCurrentUser } from "../services/user";
import { 
  createDynamic,
  getDynamicList,
  deleteDynamic,
  likeDynamic,
  unlikeDynamic,
  addComment,
  getCommentList,
  deleteComment
} from "../services/community";

// 数据模型
const showPublishPopup = ref(false);
const newPost = ref("");
const currentUser = ref(null);
const successDialogVisible = ref(false);
const createdDynamic = ref(null);
const deleteConfirmVisible = ref(false);
const pendingDeleteId = ref(null);

// 列表状态
const dynamicList = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 评论相关
const commentPopupVisible = ref(false);
const currentDynamicId = ref(null);
const commentList = ref([]);
const commentLoading = ref(false);
const commentFinished = ref(false);
const commentRefreshing = ref(false);
const commentCurrentPage = ref(1);
const commentPageSize = ref(10);
const commentTotal = ref(0);
const newComment = ref('');
const replyToComment = ref(null);
const deleteCommentConfirmVisible = ref(false);
const pendingDeleteCommentId = ref(null);

// 获取路由对象
const router = useRouter();
const route = useRoute();

onMounted(async () => {
  try {
    // 获取当前登录用户信息
    const userInfo = await getCurrentUser();
    if (userInfo) {
      currentUser.value = userInfo;
      // 初始加载动态列表
      await loadDynamicList();
      
      // 检查URL参数，如果有dynamicId则打开评论
      const dynamicId = route.query.dynamicId;
      if (dynamicId) {
        viewDynamicDetail(Number(dynamicId));
      }
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
});

// 加载动态列表
const loadDynamicList = async (isRefresh = false) => {
  if (isRefresh) {
    currentPage.value = 1;
    dynamicList.value = [];
    finished.value = false;
  }
  
  try {
    loading.value = true;
    
    const response = await getDynamicList({
      current: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'create_time',
      sortOrder: 'desc'
    });
    
    console.log("加载动态列表响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        if (response.data && response.data.records) {
          // 直接使用服务器返回的数据
          const newData = response.data.records;
          
          // 处理分页逻辑
          if (isRefresh || currentPage.value === 1) {
            // 完全重置列表，使用服务器数据
            dynamicList.value = newData;
          } else {
            // 追加新数据，但避免重复
            const existingIds = dynamicList.value.map(item => item.dynamicId);
            const uniqueNewData = newData.filter(item => !existingIds.includes(item.dynamicId));
            dynamicList.value = [...dynamicList.value, ...uniqueNewData];
          }
          
          // 更新分页信息
          currentPage.value++;
          
          // 判断是否已加载全部数据
          if (newData.length === 0 || dynamicList.value.length >= response.data.total) {
            finished.value = true;
          }
          
          console.log(`加载动态: 总数=${response.data.total}, 当前页=${currentPage.value-1}, 记录数=${newData.length}, 列表长度=${dynamicList.value.length}`);
        } else {
          showFailToast("获取动态列表失败：数据格式异常");
          finished.value = true;
        }
        break;
        
      case 50000: // 系统内部异常，视为错误
        showFailToast("获取动态列表时发生系统异常");
        console.error("获取动态列表返回50000错误:", response);
        finished.value = true;
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        finished.value = true;
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        finished.value = true;
        break;
        
      case 40101: // 无权限
        showFailToast("您没有查看动态列表的权限");
        finished.value = true;
        break;
        
      default:
        showFailToast(response.message || response.description || "获取动态列表失败");
        finished.value = true;
    }
  } catch (error) {
    console.error("获取动态列表失败", error);
    showFailToast("获取动态列表失败，请稍后重试");
    finished.value = true;
  } finally {
    loading.value = false;
    if (isRefresh) {
      refreshing.value = false;
    }
  }
};

// 下拉刷新
const onRefresh = async () => {
  await loadDynamicList(true);
};

// 上拉加载更多
const onLoad = async () => {
  if (!finished.value) {
    await loadDynamicList();
  }
};

// 显示发布动态弹窗
const showPublish = () => {
  if (!currentUser.value) {
    showFailToast("请先登录");
    router.push("/user/login");
    return;
  }
  
  showPublishPopup.value = true;
  newPost.value = "";
};

// 发布动态
const publishPost = async () => {
  if (!newPost.value.trim()) {
    showFailToast("内容不能为空");
    return;
  }
  
  const loading = showLoadingToast({
    message: "发布中...",
    forbidClick: true
  });
  
  try {
    // 调用创建动态API
    const response = await createDynamic({
      content: newPost.value
    });
    
    console.log("发布动态响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        try {
          // 判断是否有有效数据返回，可能是data字段或response本身
          const dynamicId = response.data || response;
          
          // 动态ID验证
          if (!dynamicId) {
            throw new Error("返回的动态ID无效");
          }
          
          const realDynamicId = typeof dynamicId === 'object' ? dynamicId.id || dynamicId : dynamicId;
          
          // 保存创建的动态ID（仅用于UI展示，不参与列表渲染）
          createdDynamic.value = {
            dynamicId: realDynamicId,
            content: newPost.value,
            createTime: new Date().toLocaleString()
          };
          
          console.log("动态创建成功，ID:", realDynamicId);
          
          // 清理表单
          showPublishPopup.value = false;
          newPost.value = "";
          
          // 显示成功对话框
          successDialogVisible.value = true;
          
          // 刷新动态列表，确保从服务器获取最新数据
          await loadDynamicList(true);
          
          // 可选：检查新创建的动态是否真的在列表中
          const found = dynamicList.value.some(item => item.dynamicId == realDynamicId);
          if (!found) {
            console.warn("新创建的动态未在列表中找到，ID:", realDynamicId);
          }
        } catch (verifyError) {
          console.error("动态创建后验证失败:", verifyError);
          showFailToast("动态可能未正确创建，请稍后查看或重新发布");
        }
        break;
        
      case 50000: // 系统内部异常，视为错误
        showFailToast("系统内部异常，发布可能失败，请稍后再试");
        console.error("发布动态返回50000错误:", response);
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误，请检查输入内容");
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有发布权限");
        break;
        
      case 50001: // 插入数据失败
        showFailToast("数据库操作失败，请稍后重试");
        break;
        
      default:
        showFailToast(response.message || response.description || "发布失败");
    }
  } catch (error) {
    console.error("发布失败", error);
    showFailToast("发布失败，请稍后重试");
  } finally {
    loading.close();
  }
};

// 查看动态详情
const viewDynamicDetail = (dynamicId) => {
  // 显示评论弹窗
  currentDynamicId.value = dynamicId;
  commentList.value = [];
  commentCurrentPage.value = 1;
  commentFinished.value = false;
  commentTotal.value = 0;
  newComment.value = '';
  replyToComment.value = null;
  
  // 打开评论弹窗
  commentPopupVisible.value = true;
  
  // 加载评论
  loadComments();
};

// 加载评论
const loadComments = async () => {
  if (!currentDynamicId.value) return;
  
  try {
    commentLoading.value = true;
    
    const response = await getCommentList(currentDynamicId.value, {
      current: commentCurrentPage.value,
      pageSize: commentPageSize.value
    });
    
    console.log("加载评论列表响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        if (response.data && response.data.records) {
          // 处理分页逻辑
          if (commentCurrentPage.value === 1) {
            // 完全重置列表
            commentList.value = response.data.records;
          } else {
            // 追加新数据，但避免重复
            const existingIds = commentList.value.map(item => item.commentId);
            const uniqueNewData = response.data.records.filter(
              item => !existingIds.includes(item.commentId)
            );
            commentList.value = [...commentList.value, ...uniqueNewData];
          }
          
          // 更新分页信息和总数
          commentCurrentPage.value++;
          commentTotal.value = response.data.total;
          
          // 判断是否已加载全部数据
          if (response.data.records.length === 0 || commentList.value.length >= response.data.total) {
            commentFinished.value = true;
          }
        } else {
          showFailToast("获取评论列表失败：数据格式异常");
          commentFinished.value = true;
        }
        break;
        
      case 50000: // 系统内部异常，视为错误
        showFailToast("获取评论列表时发生系统异常");
        console.error("获取评论列表返回50000错误:", response);
        commentFinished.value = true;
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        commentFinished.value = true;
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        commentFinished.value = true;
        break;
        
      default:
        showFailToast(response.message || response.description || "获取评论列表失败");
        commentFinished.value = true;
    }
  } catch (error) {
    console.error("获取评论列表失败", error);
    showFailToast("获取评论列表失败，请稍后重试");
    commentFinished.value = true;
  } finally {
    commentLoading.value = false;
    commentRefreshing.value = false;
  }
};

// 刷新评论
const refreshComments = async () => {
  commentCurrentPage.value = 1;
  commentList.value = [];
  commentFinished.value = false;
  await loadComments();
};

// 加载更多评论
const loadMoreComments = async () => {
  if (!commentFinished.value) {
    await loadComments();
  }
};

// 显示回复输入框
const showReplyInput = (comment) => {
  replyToComment.value = comment;
  newComment.value = `回复 @${comment.user.username}: `;
  // 让输入框获取焦点
  setTimeout(() => {
    document.querySelector('.comment-input input').focus();
  }, 100);
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    showFailToast("评论内容不能为空");
    return;
  }
  
  if (!currentUser.value) {
    showFailToast("请先登录");
    router.push("/user/login");
    return;
  }
  
  try {
    const loading = showLoadingToast({
      message: "发送中...",
      forbidClick: true
    });
    
    const commentData = {
      dynamicId: currentDynamicId.value,
      content: newComment.value,
      parentId: replyToComment.value ? replyToComment.value.commentId : null
    };
    
    const response = await addComment(commentData);
    
    console.log("发表评论响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        showSuccessToast("评论成功");
        newComment.value = '';
        
        // 如果是回复评论，需要处理回复列表
        if (replyToComment.value && response.data) {
          // 可以在这里处理回复评论的显示，但通常我们会刷新整个评论列表
          console.log("回复评论成功:", response.data);
        }
        
        replyToComment.value = null;
        
        // 刷新评论列表
        await refreshComments();
        
        // 更新当前动态的评论数
        const currentDynamic = dynamicList.value.find(item => item.dynamicId === currentDynamicId.value);
        if (currentDynamic) {
          currentDynamic.commentCount = (currentDynamic.commentCount || 0) + 1;
        }
        
        // 更新评论总数
        commentTotal.value += 1;
        break;
        
      case 50000: // 系统内部异常
        showFailToast("系统内部异常，评论可能失败");
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有评论权限");
        break;
        
      default:
        showFailToast(response.message || response.description || "评论失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("评论失败", error);
    showFailToast("评论失败，请稍后重试");
  }
};

// 点赞/取消点赞动态
const toggleLike = async (item) => {
  if (!currentUser.value) {
    showFailToast("请先登录");
    router.push("/user/login");
    return;
  }
  
  try {
    const loading = showLoadingToast({
      message: item.hasLiked ? "取消点赞中..." : "点赞中...",
      forbidClick: true
    });
    
    const response = item.hasLiked 
      ? await unlikeDynamic(item.dynamicId)
      : await likeDynamic(item.dynamicId);
    
    console.log("点赞/取消点赞响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        // 更新UI显示
        item.hasLiked = !item.hasLiked;
        item.likeCount = item.hasLiked 
          ? (item.likeCount + 1) 
          : (item.likeCount > 0 ? item.likeCount - 1 : 0);
          
        // 操作成功提示
        const actionText = item.hasLiked ? "点赞成功" : "取消点赞成功";
        showSuccessToast(actionText);
        break;
        
      case 50000: // 系统内部异常，但操作可能已成功
        // 如果是50000错误码，视为成功但有警告
        showSuccessToast("操作已执行，但系统返回警告");
        
        // 更新UI显示
        item.hasLiked = !item.hasLiked;
        item.likeCount = item.hasLiked 
          ? (item.likeCount + 1) 
          : (item.likeCount > 0 ? item.likeCount - 1 : 0);
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40001: // 请求数据为空
        showFailToast("动态不存在或已被删除");
        // 从列表中移除不存在的动态
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== item.dynamicId
        );
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有操作权限");
        break;
        
      case 50001: // 插入数据失败
        showFailToast("数据库操作失败，请稍后重试");
        break;
        
      default:
        showFailToast(response.message || response.description || "操作失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("点赞操作失败", error);
    showFailToast("操作失败，请稍后重试");
  }
};

// 确认删除动态
const confirmDelete = (dynamicId) => {
  if (!currentUser.value) {
    showFailToast("请先登录");
    return;
  }
  
  pendingDeleteId.value = dynamicId;
  deleteConfirmVisible.value = true;
};

// 确认删除后执行删除
const deleteConfirmed = async () => {
  if (!pendingDeleteId.value) return;
  
  try {
    const loading = showLoadingToast({
      message: "删除中...",
      forbidClick: true
    });
    
    const response = await deleteDynamic(pendingDeleteId.value);
    console.log("删除动态响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        showSuccessToast("删除成功");
        
        // 从列表中移除已删除的动态
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 50000: // 系统内部异常，但操作可能已成功
        showSuccessToast("删除可能已成功，但系统返回警告");
        
        // 从列表中移除动态（假设已删除）
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40001: // 请求数据为空
        showFailToast("动态不存在或已被删除");
        // 从列表中移除不存在的动态
        dynamicList.value = dynamicList.value.filter(
          item => item.dynamicId !== pendingDeleteId.value
        );
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有权限删除此动态");
        break;
        
      case 50001: // 插入数据失败
        showFailToast("数据库操作失败，请稍后重试");
        break;
        
      default:
        showFailToast(response.message || response.description || "删除失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("删除动态失败", error);
    showFailToast("删除失败，请稍后重试");
  } finally {
    pendingDeleteId.value = null;
  }
};

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 大于30天，显示具体日期
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
};

// 确认删除评论
const confirmDeleteComment = (comment) => {
  if (!currentUser.value) {
    showFailToast("请先登录");
    return;
  }
  
  pendingDeleteCommentId.value = comment.commentId;
  deleteCommentConfirmVisible.value = true;
};

// 确认删除后执行删除评论
const deleteCommentConfirmed = async () => {
  if (!pendingDeleteCommentId.value) return;
  
  try {
    const loading = showLoadingToast({
      message: "删除中...",
      forbidClick: true
    });
    
    const response = await deleteComment(pendingDeleteCommentId.value);
    console.log("删除评论响应:", response);
    
    // 统一处理响应状态码
    switch(response.code) {
      case 0: // 成功
        showSuccessToast("删除成功");
        
        // 从列表中移除已删除的评论
        commentList.value = commentList.value.filter(
          item => item.commentId !== pendingDeleteCommentId.value
        );
        
        // 更新评论总数
        commentTotal.value = Math.max(0, commentTotal.value - 1);
        
        // 更新当前动态的评论数
        const dynamicToUpdate = dynamicList.value.find(item => item.dynamicId === currentDynamicId.value);
        if (dynamicToUpdate && dynamicToUpdate.commentCount > 0) {
          dynamicToUpdate.commentCount -= 1;
        }
        break;
        
      case 50000: // 系统内部异常，但操作可能已成功
        showSuccessToast("删除可能已成功，但系统返回警告");
        
        // 从列表中移除评论（假设已删除）
        commentList.value = commentList.value.filter(
          item => item.commentId !== pendingDeleteCommentId.value
        );
        
        // 更新评论总数
        commentTotal.value = Math.max(0, commentTotal.value - 1);
        
        // 更新当前动态的评论数
        const dynamicToUpdateAlt = dynamicList.value.find(item => item.dynamicId === currentDynamicId.value);
        if (dynamicToUpdateAlt && dynamicToUpdateAlt.commentCount > 0) {
          dynamicToUpdateAlt.commentCount -= 1;
        }
        break;
        
      case 40000: // 请求参数错误
        showFailToast("请求参数错误");
        break;
        
      case 40001: // 请求数据为空
        showFailToast("评论不存在或已被删除");
        // 从列表中移除不存在的评论
        commentList.value = commentList.value.filter(
          item => item.commentId !== pendingDeleteCommentId.value
        );
        break;
        
      case 40100: // 未登录
        showFailToast("请先登录");
        router.push("/user/login");
        break;
        
      case 40101: // 无权限
        showFailToast("您没有权限删除此评论");
        break;
        
      default:
        showFailToast(response.message || response.description || "删除失败");
    }
    
    loading.close();
  } catch (error) {
    console.error("删除评论失败", error);
    showFailToast("删除失败，请稍后重试");
  } finally {
    pendingDeleteCommentId.value = null;
  }
};
</script>

<style lang="scss" scoped>
.community-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 50px;
}

.page-content {
  padding: 8px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.dynamic-item {
  margin-bottom: 12px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.dynamic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.name-time {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.time {
  font-size: 12px;
  color: #999;
}

.options {
  color: #666;
  font-size: 18px;
}

.dynamic-content {
  margin-bottom: 16px;
}

.text {
  font-size: 15px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 12px;
  word-break: break-all;
}

.notice-text {
  margin-top: 10px;
  padding: 5px 0;
  font-size: 12px;
}

.dynamic-footer {
  display: flex;
  border-top: 1px solid #f2f2f2;
  padding-top: 12px;
}

.action-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #666;
  gap: 6px;
}

.publish-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f2f2f2;
}

.publish-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.publish-notice {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.publish-content {
  padding: 16px;
}

.publish-textarea {
  font-size: 15px;
  margin-bottom: 16px;
}

.publish-media {
  margin-top: 16px;
}

.publish-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 16px 16px;
}

.success-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.success-info p {
  margin: 10px 0;
}

.dynamic-info {
  width: 100%;
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.dynamic-info p {
  font-size: 14px;
  margin: 8px 0;
  color: #333;
}

.delete-confirm-text {
  padding: 20px;
  text-align: center;
  color: #666;
}

/* 评论相关样式 */
.comment-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f2f2f2;
}

.comment-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.comment-list-container {
  height: calc(100% - 110px);
  overflow-y: auto;
  padding: 0 16px;
}

.empty-comment {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #f2f2f2;
}

.comment-user-info, .reply-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-avatar, .reply-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
}

.reply-avatar {
  width: 28px;
  height: 28px;
}

.comment-user-detail, .reply-user-detail {
  flex: 1;
}

.comment-username, .reply-username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.comment-time, .reply-time {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.comment-like, .reply-like {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.comment-content, .reply-content {
  padding-left: 48px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 8px;
}

.reply-content {
  padding-left: 40px;
}

.reply-list {
  background-color: #f8f8f8;
  border-radius: 8px;
  margin: 8px 0 8px 48px;
  padding: 8px;
}

.reply-item {
  padding: 8px 0;
  border-bottom: 1px solid #f2f2f2;
}

.reply-item:last-child {
  border-bottom: none;
}

.comment-actions {
  padding-left: 48px;
  display: flex;
  justify-content: flex-start;
}

.comment-input-container {
  position: sticky;
  bottom: 0;
  background-color: #fff;
  border-top: 1px solid #f2f2f2;
  padding: 8px 16px;
}

.comment-input {
  width: 100%;
}

.comment-actions-top {
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-icon {
  color: #999;
  font-size: 16px;
}
</style>
